<!DOCTYPE html>
<%--
Copyright (c) 2012 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ page
    import="com.google.api.client.auth.oauth2.Credential" %>
<%@ page import="com.google.api.client.auth.oauth2.BearerToken" %>
<%@ page import="com.google.api.client.auth.oauth2.TokenResponse" %>
<%@ page import="com.google.api.services.plus.Plus" %>
<%@ page import="com.google.api.services.plus.Plus.Builder" %>
<%@ page import="com.google.api.services.plus.model.*" %>
<%@ page import="com.google.api.sample.ConfigHelper" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.commons.lang3.StringEscapeUtils" %>
<%@ page import="com.google.api.sample.Util" %>
<%@ page import="com.google.api.client.http.HttpResponseException" %>
<%@ page import="java.util.logging.Logger" %>
<%@ page import="com.google.api.client.http.json.JsonHttpRequestInitializer" %>
<%@ page import="com.google.api.client.http.json.JsonHttpRequest" %>
<%@ page import="java.io.IOException" %>
<%@ page import="com.google.api.services.plus.PlusRequest" %>
<% final Logger LOG = Logger.getLogger("/index.jsp"); %>

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Google+ platform Java Starter App</title>
  <link rel="stylesheet" href="style.css" type="text/css"/>
</head>
<body>
<header><h1>Google+ platform Java Starter App</h1></header>

<div class="largerbox">
  <% if (Util.getFlow().loadCredential(session.getId()) == null) { %>
  <a class='login' href='connect'>Connect Me!</a>
  <% } else { %>
  <p>Your OAuth 2.0 token is in <code>session.accessToken</code>.</p>

  <p class="logout"><a href="clearsession">Logout</a> by deleting this token.
  </p>

  <%
    // Here's an example of an unauthenticated Plus object. In cases where you
    // do not need to use the /me/ path segment to discover the current user's
    // ID, you can skip the OAuth flow with this code.
    Plus.Builder builder = new Plus.Builder(Util.TRANSPORT, Util.JSON_FACTORY, null);
    
    // When we do not specify access tokens, we must specify our API key instead
    // We do this using a JsonHttpRequestInitializer
    Plus unauthenticatedPlus = builder.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
          public void initialize(JsonHttpRequest jsonHttpRequest) throws IOException {
            PlusRequest plusRequest = (PlusRequest) jsonHttpRequest;
            plusRequest.setKey(ConfigHelper.GOOGLE_API_KEY);
          }
        }).build();

    // If, however, you need to use OAuth to identify the current user you must
    // create the Plus object differently. Most programs will need only one
    // of these since you can use an authenticated Plus object for any call
    Credential credential = Util.getFlow().loadCredential(session.getId());
    
    builder = new Plus.Builder(Util.TRANSPORT, Util.JSON_FACTORY, credential);

    Plus plus = builder.build();

  %>
  <section class="activity">
    <h3>A Specific Public Activity</h3>
    <%
      // Fetch a specific known public activity
      String publicActivityId = "z12gtjhq3qn2xxl2o224exwiqruvtda0i";
      Activity publicActivity;
      try {
        publicActivity = unauthenticatedPlus
            .activities().get(publicActivityId).execute();
      } catch (HttpResponseException e) {
        LOG.severe(e.getLocalizedMessage());
        return;
      }
      // Render it
    %>
    <dl>
      <dt>ID</dt>
      <dd>
        <a href="<%= publicActivity.getUrl() %>"><%= publicActivity.getId() %>
        </a>
      </dd>
      <dt>Contents</dt>
      <dd>
        <%= StringEscapeUtils.escapeHtml4(
            Util.stripTags(publicActivity.getObject().getContent())) %>
      </dd>
    </dl>

  </section>
</div>
<div class="box">
  <section class="me">
    <%
      //fetch your profile object
      Person profile;
      try {
        profile = plus.people().get("me").execute();
      } catch (HttpResponseException e) {
        LOG.severe(e.getLocalizedMessage());
        return;
      }

      //render it
    %>
    <h3>Your Profile</h3>
    <dl>
      <dt>Image</dt>
      <dd><a href="<%= profile.getUrl() %>">
        <img src="<%= profile.getImage().getUrl() %>"/></a>
      </dd>
      <dt>ID</dt>
      <dd><%= profile.getId() %>
      </dd>
      <dt>Name</dt>
      <dd>
        <a href="<%= profile.getUrl() %>">
          <%= StringEscapeUtils.escapeHtml4(profile.getDisplayName()) %>
        </a>
      </dd>
    </dl>
  </section>
</div>
<div class="largerbox">
  <section class="activity_list">
    <h3>Your Public Activity</h3>
    <%
      Plus.Activities.List listActivities = plus.activities().list("me", "public");
      listActivities.setMaxResults(5L);
      // Pro tip: Use partial responses to improve response time considerably
      listActivities.setFields("nextPageToken,items(id,url,object/content)");

      ActivityFeed activityFeed;
      try {
        activityFeed = listActivities.execute();
      } catch (HttpResponseException e) {
        LOG.severe(e.getLocalizedMessage());
        return;
      }

      List<Activity> activities = activityFeed.getItems();

      listActivities.setPageToken(activityFeed.getNextPageToken());

      // Keep track of the page number in case we're listing activities
      // for a user with thousands of activities. We'll limit ourselves
      // to 5 pages
      int currentPageNumber = 0;
    %>
    <table>
      <thead>
      <tr>
        <th>ID</th>
        <th>Content</th>
      </tr>
      </thead>
      <tbody>
      <%
        while (activities != null && currentPageNumber < 5) {
          currentPageNumber++;

          if (activityFeed.getItems() != null) {
            for (Activity activity : activities) {
      %>
      <tr>
        <td><a href="<%= activity.getUrl() %>"><%= activity.getId() %>
        </a></td>
        <td><%= StringEscapeUtils.escapeHtml4(
            Util.stripTags(activity.getObject().getContent())) %>
        </td>
      </tr>
      <%
              }
              // We will know we are on the last page when the next page token is null.
              // If this is the case, break.
              if (activityFeed.getNextPageToken() == null) {
                break;
              }
              // Prepare the next page of results
              listActivities.setPageToken(activityFeed.getNextPageToken());
              // Execute and process the next page request
              try {
                activityFeed = listActivities.execute();
              } catch (HttpResponseException e) {
                LOG.severe(e.getLocalizedMessage());
                return;
              }

              activities = activityFeed.getItems();
            }
          }
        }
      %>
      </tbody>
    </table>
  </section>
</div>
</body>
</html>
